# Created by xiaosanyu at 16/5/30

# https://docs.mongodb.com/ecosystem/drivers/python/
# https://pypi.python.org/pypi/pymongo/

import pymongo
from pymongo.mongo_client import MongoClient
import pymongo.errors
import traceback

class MongDBHandle:
    def Connect_DB(config):
        mongoDatabase = None
        try:
            # 连接到 mongodb 服务
            mongoClient = MongoClient(config.ip, config.port)
            # 连接到数据库
            mongoDatabase = mongoClient.test
            print("connect database successfully")

        except pymongo.errors.PyMongoError as e:
            print("mongo Error:", e)
            mongoDatabase = None
            traceback.print_exc()
        return mongoDatabase
    
    def CreatTable_DB(mongoDatabase, dataList):
        if None is mongoDatabase:
            print("mongo create table Error")
            return False
        try:
            # 获取集合
            mongoCollection = mongoDatabase.COMPANY
            # 移除所有数据
            mongoCollection.remove()
            # 添加数据
            mongoCollection.insert_many(dataList)
        except pymongo.errors.PyMongoError as e:
            print("mongo create table Error:", e)
            traceback.print_exc()
            return False
        return True
    
    def InsertData_DB(mongoDatabase, dataList):
        if None is mongoDatabase:
            print("mongo insert Error")
            return False
        try:
            # 获取集合
            mongoCollection = mongoDatabase.COMPANY
            # 添加数据
            mongoCollection.insert_many(dataList)
        except pymongo.errors.PyMongoError as e:
            print("mongo insert table Error:", e)
            traceback.print_exc()
            return False
        return True

    def Clear_DB(mongoDatabase):
        if None is mongoDatabase:
            print("mongo clear Error")
            return False
        # 获取集合
        mongoCollection = mongoDatabase.COMPANY
        # 移除所有数据
        mongoCollection.remove()
        return True

class MongDBConfig:
    ip = 'localhost'
    port = 27017

def MongDBTest():
    try:
        # 连接到 mongodb 服务
        mongDBHandle = MongDBHandle();
        mongoDatabase = mongDBHandle.Connect_DB('localhost', 27017)

        # 获取集合
        mongoCollection = mongoDatabase.COMPANY

        # 移除所有数据
        mongoCollection.remove()

        # 添加数据
        mongoCollection.insert_many([{"Name": "Paul", "Age": "32", "Address": "California", "Salary": "20000.00"},
                                    {"Name": "Allen", "Age": "25", "Address": "Texas", "Salary": "15000.00"},
                                    {"Name": "Teddy", "Age": "23", "Address": "Norway", "Salary": "20000.00"},
                                    {"Name": "Mark", "Age": "25", "Address": "Rich-Mond", "Salary": "65000.00"},
                                    {"Name": "David", "Age": "27", "Address": "Texas", "Salary": "85000.00"},
                                    {"Name": "Kim", "Age": "22", "Address": "South-Hall", "Salary": "45000.00"},
                                    {"Name": "James", "Age": "24", "Address": "Houston", "Salary": "10000.00"}, ])

        #获取集合中的值
        for row in mongoCollection.find():
            print("-" * 50)  # 输出50个-,作为分界线
            print("%-10s %s" % ("_id", row['_id']))  # 字段名固定10位宽度,并且左对齐
            print("%-10s %s" % ("name", row['Name']))
            print("%-10s %s" % ("age", row['Age']))
            print("%-10s %s" % ("address", row['Address']))
            print("%-10s %s" % ("salary", row['Salary']))

        print('\n\n\n')
        # 使id自增
        mongoCollection.remove()
        # 创建计数表
        mongoDatabase.counters.save({"_id": "people_id", "sequence_value": 0})
        # 创建存储过程
        mongoDatabase.system_js.getSequenceValue = '''function getSequenceValue(sequenceName){
                var sequenceDocument = db.counters.findAndModify({
                    query: {_id: sequenceName},
                    update: {$inc:{sequence_value: 1}},
                    new:true
                });
                return sequenceDocument.sequence_value;
            }'''
        mongoCollection.insert_many(
                [{"_id": mongoDatabase.eval("getSequenceValue('people_id')"), "Name": "Paul", "Age": "32",
                "Address": "California", "Salary": "20000.00"},
                {"_id": mongoDatabase.eval("getSequenceValue('people_id')"), "Name": "Allen", "Age": "25",
                "Address": "Texas", "Salary": "15000.00"},
                {"_id": mongoDatabase.eval("getSequenceValue('people_id')"), "Name": "Teddy", "Age": "23",
                "Address": "Norway", "Salary": "20000.00"},
                {"_id": mongoDatabase.eval("getSequenceValue('people_id')"), "Name": "Mark", "Age": "25",
                "Address": "Rich-Mond", "Salary": "65000.00"},
                {"_id": mongoDatabase.eval("getSequenceValue('people_id')"), "Name": "David", "Age": "27",
                "Address": "Texas", "Salary": "85000.00"},
                {"_id": mongoDatabase.eval("getSequenceValue('people_id')"), "Name": "Kim", "Age": "22",
                "Address": "South-Hall", "Salary": "45000.00"},
                {"_id": mongoDatabase.eval("getSequenceValue('people_id')"), "Name": "James", "Age": "24",
                "Address": "Houston", "Salary": "10000.00"}, ])

        for row in mongoCollection.find():
            print("-" * 50)  # 输出50个-,作为分界线
            print("%-10s %s" % ("_id", int(row['_id'])))  # 字段名固定10位宽度,并且左对齐
            print("%-10s %s" % ("name", row['Name']))
            print("%-10s %s" % ("age", row['Age']))
            print("%-10s %s" % ("address", row['Address']))
            print("%-10s %s" % ("salary", row['Salary']))
    except pymongo.errors.PyMongoError as e:
        print("mongo Error:", e)
        traceback.print_exc()


if __name__ == "__main__":
    try:
        # 连接到 mongodb 服务
        mongDBHandle = MongDBHandle();
        mongoDatabase = mongDBHandle.Connect_DB('localhost', 27017)
    except pymongo.errors.PyMongoError as e:
        print("mongo Error:", e)
        traceback.print_exc()